/**
 * @description 路由导航守卫
 * @author Zhangbin
 */
import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
import router from './router'
import store from '@/store'
const { getters, dispatch } = store;

// progress bar
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false });
//

const whiteList: Array<string> = ['/auth-redirect']; // 登录白名单

//
router.isReady().then(() => {
  // resolve the request

}).catch((error: any) => {
  // error
});

// 路由拦截
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    // 白名单
    if (~whiteList.indexOf(to.path)) {
      next();
      return;
    }
    //
    //
    NProgress.start();

    if (getters.userInfo.token) {
      if (to.path === '/login') {
        // 如果已经登录，重定向到首页
        next({ path: '/home' })
      } else {
        if (getters.asyncRoutes.length === 0) {
          try {
            await dispatch('ASYNC_ROUTER');
            // 添加路由
            getters.asyncRoutes.forEach((route: any) => {
              router.addRoute(route)
            });
            next({ ...to })
          } catch (error) {
            console.error(error);
            await dispatch("CLEAR_ALLDATA", {});
            next(`/login?redirect=${to.path}`)
          }
        } else {
          next()
        }
      }
    } else {
      if (to.path === '/login') {
        next()
      } else {
        next({ path: '/login' });
      }
    }
  }
);

router.afterEach(
  (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized
  ) => {
    // Finish progress bar
    NProgress.done()
  }
);
//